iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
1

本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (21) 建立購物車系統 - 4

1. 安裝Swagger

在CartApi專案右鍵[管理NuGet套件],安裝Swagger相關的套件::

Swashbuckle.AspNetCore.SwaggerGen , 版本 5.6.1

Swashbuckle.AspNetCore.SwaggerUI , 版本 5.6.1

2. 在Startup.cs註冊與使用Swagger

2.1 ConfigureServices的服務註冊

需使用SwaggerGen註冊Swagger的功能,並加上對此Api專案的描述。

    public void ConfigureServices(IServiceCollection services)
    {
    	// other code...
    	
    	services.AddSwaggerGen(options => {
                    options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                    {
                        Version = "v1",
                        Title = "Cart HTTP API",
                        Description = "The Cart Service HTTP API"
                    });
                });
    }

2.2 Configure加上Swagger的Middleware

在Pipeline加上Swagger的Middleware,放在app.UseRouting之前,指定它的json endpoint與名稱。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	// other code...

	app.UseSwagger()
             .UseSwaggerUI(c =>
             {
                 c.SwaggerEndpoint(
                     $"/swagger/v1/swagger.json",
                     "Cart.API V1");
             });

	app.UseRouting();

	// other code...
}

3. 修改launchSettings.json

從VS執行程式的參數會依照launchSettings.json,包含URL與其他環境變數。而原先預設在IIS Express的launchUrl是weatherforecast,將它改成swagger,這樣VS啟用IIS的設定會用swagger:

    {
      "$schema": "http://json.schemastore.org/launchsettings.json",
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:1028",
          "sslPort": 0
        }
      },
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "CartApi": {
          "commandName": "Project",
          "launchBrowser": true,
          "applicationUrl": "http://localhost:5000",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }

4. 移除預設專案的範例

原先建立CartApi專案時,會有WeatherForecast的Controller與Model,將這些都移除。

5. 修改docker-compose.yml

在docker-compose.yml新增redis的container,service的名字為cart.data,內部6379 port對應本機的 6377 port:

    version: "3.4"
    
    networks:
       frontend:
       backend:
       
    services:
       webmvc:
          build:
             context: .\src\Presentation\WebMvc
             dockerfile: Dockerfile
          environment:
             - CatalogUrl=http://catalog
             - IdentityUrl=https://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7101
             - CallBackUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7500/
          container_name: rpgwebmvc
          ports:
             - "7500:80"
          networks:
             - frontend
          depends_on:
             - catalog
             - auth
    
       catalog:
          build:
             context: .\src\Services\CatalogApi
             dockerfile: Dockerfile
          image: rpgshop/catalog
          environment:
             - DatabaseServer=mssqlserver
             - DatabaseName=CatalogDb
             - DatabaseUser=sa
             - DatabasePassword=JustTest!
             - ExternalCatalogBaseUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7000
          container_name: rpgcatalogapi
          ports:
             - "7000:80"
          networks:
             - backend
             - frontend
          depends_on:
             - mssqlserver
    
       auth:
          build:
             context: .\src\Services\AuthApi
             dockerfile: Dockerfile
          image: rpgshop/auth
          environment:
             - MvcClient=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7500
             - DatabaseServer=mssqlserver
             - DatabaseName=AuthDb
             - DatabaseUser=sa
             - DatabasePassword=JustTest!
             - ExternalCatalogBaseUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7000
             - ASPNETCORE_URLS=http://+:80;https://+:443
             - ASPNETCORE_Kestrel__Certificates__Default__Password=crypticpassword
             - ASPNETCORE_Kestrel__Certificates__Default__Path=./AuthApi.pfx
          container_name: rpgauthapi
          ports:
             - "7100:80"
             - "7101:443"
          networks:
             - backend
             - frontend
          depends_on:
             - mssqlserver
    
       mssqlserver:
          image: "microsoft/mssql-server-linux:latest"
          ports:
             - "1445:1433"
          container_name: rpgmssqlcontainer
          environment:
             - ACCEPT_EULA=Y
             - SA_PASSWORD=JustTest!
          networks:
             - backend
    
       cart.data:
          image: redis
          ports:
             - "6377:6379"
          networks:
             - backend

6. 執行docker-compose啟用redis

  目前只需要執行redis,所以在docker-compose.yml的目錄使用cmd執行:

docker-compose up cart.data

7. VS執行

將CartApi設為預設專案並開啟Debug,看到畫面是Swagger的介面,包含我們所寫的Controller的Action,如圖1。每個API都能點擊,並按下Try it out的按鈕,輸入參數做實際的API運作。

圖1

比如點Http Post的/api/Cart,新增一筆Buyer Id對應的購物車商品列表,再用Http Get的/api/Cart/{id}取得該Buyer Id的資料,再用Http Delete的/api/Cart/{id}刪除該物件。


上一篇
[Day20] 建立購物車系統 - 3
下一篇
[Day22] 建立購物車系統 - 5
系列文
一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言